package com.itheima.controller;

import com.alibaba.fastjson.JSON;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    //所有servlet的基础


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取访问地址
        String requestURI = request.getRequestURI();  //获取到这个访问地址：/brand/selectAll
        //2.获取最后一个/的位置
        int index = requestURI.lastIndexOf("/");
        //3.获取/后面开始的子字符串，这个字符串就是方法的名字
        String methodName = requestURI.substring(index + 1);

        //4.通过反射来调用方法
        //4.1 获取当前Servlet的类对象
        Class<? extends Servlet> servletClass = this.getClass();
        try {
            //4.2 通过名字获取方法对象
            Method method = servletClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println("Servlet中调用方法：" + method);
            //4.3 通过反射调用方法
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param request 浏览器的请求对象
     * @param objectClass 要转换的实体类的class类对象
     * @param <T> 使用泛型
     * @return obj 返回是是同归json转化后的实体类的对象
     */
    public <T> T getJsonByStr(HttpServletRequest request, Class<T> objectClass){
        String json = null;
        try {
            //1,获取前端发来的json
            json = request.getReader().readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.将json转化为实体类
        T obj = JSON.parseObject(json, objectClass);
        //3.将转化完成的对象返回
        return obj;
    }

    /**
     * 将实体类转化为json并发送给浏览器
     * @param obj 实体类对象
     * @param response 浏览器的响应对象
     */
    public void sendJson(Object obj, HttpServletResponse response) throws IOException {
        //1.将数据设置成json格式
        response.setContentType("application/json;charset=utf-8");
        //2.将对象转化为json
        String json = JSON.toJSONString(obj);
        //3.获取输出流
        PrintWriter out = response.getWriter();
        out.println(json);
    }

}
